﻿#pragma once
#include"tree.h"
BTNode* BuyNode(BTDataType c)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	assert(node);
	node->_data = c;
	node->_left = node->_right = NULL;
	return node;
}
// 通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
BTNode* BinaryTreeCreate(BTDataType* a, int n, int* pi)
{
	if ((*pi) >= n)
	{
		return NULL;
	}
	BTNode* root = a[*pi];
	(*pi)++;
	root->_left = BinaryTreeCreate(a, n, pi);
	root->_right = BinaryTreeCreate(a, n, pi);

	return root;
}
// 二叉树销毁
void BinaryTreeDestory(BTNode** root)
{
	assert(*root);
	BinaryTreeDestory((*root)->_left);
	BinaryTreeDestory((*root)->_right);

	free(*root);
	*root = NULL;
}
// 二叉树节点个数
int BinaryTreeSize(BTNode* root)
{

	return root == NULL ? 0 : 1 + BinaryTreeSize(root->_left) + BinaryTreeSize(root->_right);
}
// 二叉树叶子节点个数
int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->_left == NULL && root->_data == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->_left) + BinaryTreeLeafSize(root->_right);
}
// 二叉树第k层节点个数
int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (k == 0 || root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->_left, k - 1) + BinaryTreeLevelKSize(root->_right, k - 1);
}
// 二叉树查找值为x的节点
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
	{
		return NULL;
	}
	if (root->_data == x)
	{
		return root;
	}
	BTNode* left = BinaryTreeFind(root->_left, x);
	BTNode* right = BinaryTreeFind(root->_right, x);
	if (left)
	{
		return left;
	}
	if (right)
	{
		return right;
	}
	return NULL;
}

// 二叉树前序遍历 
void BinaryTreePrevOrder(BTNode* root)
{
	if (root == NULL)
		return;
	printf("%c->", root->_data);
	BinaryTreePrevOrder(root->_left);
	BinaryTreePrevOrder(root->_right);
}
// 二叉树中序遍历
void BinaryTreeInOrder(BTNode* root);
// 二叉树后序遍历
void BinaryTreePostOrder(BTNode* root);
// 层序遍历
void BinaryTreeLevelOrder(BTNode* root)
{
	if (root == NULL)
		return;
	QN queue;
	QNInit(&queue);
	QNPush(&queue, root);
	while (!QNEmpty(&queue))
	{
		BTNode* ch = QNFront(&queue);
		printf("%c ", ch->_data);
		QNPop(&queue);
		if (ch->_left)
		{
			QNPush(&queue, ch->_left);
		}
		if (ch->_right)
		{
			QNPush(&queue, ch->_right);
		}
	}

	QNDestroy(&queue);
}
// 判断二叉树是否是完全二叉树
int BinaryTreeComplete(BTNode* root)
{
	if (root == NULL)
		return 1;
	QN queue;
	QNInit(&queue);
	QNPush(&queue, root);

	while (!QNEmpty(&queue))
	{
		BTNode* ch = QNFront(&queue);
		QNPop(&queue);
		if (ch == NULL)
		{
			break;
		}
		QNPush(&queue, ch->_left);
		QNPush(&queue, ch->_right);
	}
	while (!QNEmpty(&queue))
	{
		BTNode* ch = QNFront(&queue);
		QNPop(&queue);
		if (ch)
		{
			return 0;
		}
	}
	return 1;
}